package com.tarena.lbs.content.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.content.dao.mapper.ArticleMapper;
import com.tarena.lbs.content.dao.repository.ArticleRepository;
import com.tarena.lbs.content.pojo.param.ArticleContentParam;
import com.tarena.lbs.content.pojo.po.ArticleSearchPO;
import com.tarena.lbs.content.pojo.query.ArticleQuery;
import com.tarena.lbs.content.pojo.vo.ArticleVO;
import com.tarena.lbs.content.service.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleRepository articleRepository;

    @Autowired
    private ArticleMapper articleMapper;
    private PageResult<ArticleVO> convertToPageResult(PageInfo<ArticleVO> pageInfo, String logMessage) {
        PageResult<ArticleVO> voPage = new PageResult<>();
        voPage.setPageNo(pageInfo.getPageNum());
        voPage.setPageSize(pageInfo.getPageSize());
        voPage.setTotal(pageInfo.getTotal());

        List<ArticleVO> vos = null;
        if (CollectionUtils.isNotEmpty(pageInfo.getList())) {
            vos = pageInfo.getList().stream().map(po -> {
                ArticleVO vo = new ArticleVO();
                BeanUtils.copyProperties(po, vo);
                return vo;
            }).collect(Collectors.toList());
        }
        voPage.setObjects(vos);
        log.info(logMessage, vos);

        return voPage;
    }

    @Override
    public PageResult<ArticleVO> pageList(ArticleQuery articleQuery) {
        PageInfo<ArticleVO> pageInfo = articleRepository.pageList(articleQuery);
        //检查非空
        if (pageInfo == null) {
            return new PageResult<>();//返回空结果而不是null
        }
        return convertToPageResult(pageInfo, "查询文章列表，出参:{}");
    }

    @Override
    public PageResult<ArticleVO> twitterPageList(ArticleQuery articleQuery) {
        PageInfo<ArticleVO> pageInfo = articleRepository.twitterPageList(articleQuery);
        //检查非空
        if (pageInfo == null) {
            return new PageResult<>();//返回空结果而不是null
        }
        return convertToPageResult(pageInfo, "推文创作页面查询文章列表，出参:{}");
    }

    @Override
    public void addArticle(ArticleContentParam param) {
        log.info("开始保存文章，参数：{}", param);
        try {
            // 参数转换：将ArticleContentParam转换为ArticleSearchPO
            ArticleSearchPO po = new ArticleSearchPO();
            BeanUtils.copyProperties(param, po);
            
            // 设置默认值
            if (param.getArticleStatus() == null) {
                po.setArticleStatus(1); // 默认待发布状态
            }
            
            if (param.getAccessCount() == null) {
                po.setAccessCount(0);
            }
            
            if (param.getLikeCount() == null) {
                po.setLikeCount(0);
            }
            
            if (param.getFavoriteCount() == null) {
                po.setFavoriteCount(0);
            }
            
            // 设置时间
            Date now = new Date();
            // 如果是新增文章，设置创建时间
            if (param.getId() == null) {
                po.setCreateTime(now);
            }
            // 更新时间总是设置为当前时间
            po.setUpdateTime(now);
            
            // 保存文章
            articleRepository.save(po);
            
            // 将生成的ID设置回param对象，便于Controller返回
            if (param.getId() == null && po.getId() != null) {
                param.setId(po.getId());
            }
            
            log.info("文章保存成功，文章ID: {}, 文章标题: {}", po.getId(), param.getArticleTitle());
        } catch (Exception e) {
            log.error("保存文章失败，文章标题：{}", param.getArticleTitle(), e);
            throw new RuntimeException("保存文章失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    public Set<String> getAllArticleLabels() {
        return articleRepository.getAllArticleLabels();
    }

    @Override
    public ArticleVO getArticleById(Integer id) {
        if (id == null) {
            throw new IllegalArgumentException("文章ID不能为空");
        }
        
        try {
            return articleRepository.getArticleById(id);
        } catch (Exception e) {
            log.error("获取文章详情失败，文章ID：{}", id, e);
            throw new RuntimeException("获取文章详情失败", e);
        }
    }

    @Override
    public void updateStatus(Integer id, Integer status) {
        if (id == null) {
            throw new IllegalArgumentException("文章ID不能为空");
        }

        if (status == null) {
            throw new IllegalArgumentException("状态不能为空");
        }

        // 检查状态值是否合法 (1:待发布, 2:已发布(上线), 3:下线)
        if (status != 1 && status != 2 && status != 3) {
            throw new IllegalArgumentException("状态值不合法，只能是1(待发布)、2(已发布)或3(下线)");
        }

        // 更新文章状态
        UpdateWrapper<ArticleSearchPO> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("article_status", status);
        updateWrapper.set("update_time", new Date());

        try {
            int rows = articleMapper.update(null, updateWrapper);
            if (rows == 0) {
                log.warn("更新文章状态失败，文章ID: {} 不存在", id);
                throw new RuntimeException("文章不存在");
            }
            log.info("更新文章状态成功，文章ID: {}, 状态: {}", id, status);
        } catch (Exception e) {
            log.error("更新文章状态异常，文章ID: {}", id, e);
            throw new RuntimeException("更新文章状态失败", e);
        }
    }

    @Override
    public void deleteArticle(Integer id) {
        if (id == null) {
            throw new IllegalArgumentException("文章ID不能为空");
        }

        try {
            int rows = articleMapper.deleteById(id);
            if (rows == 0) {
                log.warn("删除文章失败，文章ID: {} 不存在", id);
                throw new RuntimeException("文章不存在");
            }
            log.info("删除文章成功，文章ID: {}", id);
        } catch (Exception e) {
            log.error("删除文章异常，文章ID: {}", id, e);
            throw new RuntimeException("删除文章失败", e);
        }
    }

}